package com.user.query.generatorutil;
/**
 * Created by bgt on 2016/7/12.
 * 该工具可实现生成service，serviceimpl，controller文件，并生成基础版本的功能
 * 涵盖增删改查，和基础的view操作
 * 使用说明
 * 修改项目的地址为自己本地的地址（realpath，javapath）
 * 当项目目录结构发现变化时，修改basepath
 * name为实体名称
 * lname是转换为小写的实体名，用于生成包名使用
 * createtime 创建时间
 * authorname 类作者 需要更改
 * mybatisbasepath 存放工具的目录
 * 特别注意的是：此工具依赖mybatis生成工具包，和数据库驱动
 * 下载地址:链接：http://pan.baidu.com/s/1eSuoHn8 密码：6ged
 */

import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ServiceFileUtil {
    //项目目录
    private static String projectpath=System.getProperty("user.dir");
    //java目录
    private static String javapath=projectpath+"\\src\\main\\java\\";
    //工具类真实目录
    private static String realpath=javapath+"com\\user\\query\\generatorutil\\";
    //mybatis生成工具的路径
    private static String mybatisbasepath="D:\\BGT\\bgt_self_user\\work\\mybatis-generator-core-1.3.2\\mybatis-generator-core-1.3.2\\lib\\";
    //复写lib下的此文件
    private static String Mybatispath=mybatisbasepath+"generatorConfig.xml";
    //创建时间
    private static String createtime=new SimpleDateFormat("/yyyy/MM/dd/HH/mm/ss").format(new Date());
    //创建人
    private static String authorname="ricky";

    /**
     * 根据自己工具的路径处理
     d:
     cd D:\BGT\bgt_self_user\work\mybatis-generator-core-1.3.2\mybatis-generator-core-1.3.2\lib
     java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite
     */
    private static String Mybatisbat="cmd /c D: & cd "+mybatisbasepath+" & java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite";
    //private static String Mybatisbat=mybatisbasepath+"mybatis.bat";
    //包路径
    private static String basepath="com.hyrt.mckinsey";
    public static void main(String[] args) throws Exception {
        //当前项目目录
        System.out.println(System.getProperty("user.dir") );
       // String[] names={"Video","Vcomment","VideoCollect","VideoPraise","VideoRecord","Videoscore","Comment"};
        String[] names={"UserAttention"};
        // init(names);
        String[] names2={"VideoScore","VideoRecord"};
        //init2(names2,"video");
        String mysqlurl="jdbc:mysql://192.168.0.114:3306/mckinsey";
        String username="root";
        String pwd="hyrt01";
        //String[] commtable={"Video","VideoScore","VideoRecord"};
        String[] commtable={"Video"};
        String prestr="mac_";
       createMybatisXml(mysqlurl,username,pwd,basepath,commtable,prestr);
    }

    /**
     * 每个表生成一个包名
     * @param names
     * @throws Exception
     */
    public static void   init(String[] names) throws Exception {
        for (String name:names) {
            name=name.replace("_","");//去掉下划线
            String lname=exChange(name);
            System.out.println(lname);
            String en=basepath+"."+"comm.model."+name;
            String packagesevice=basepath+"."+lname+".service";
            String packagecontroller=basepath+"."+lname+".controller";
            String servicemapper=basepath+"."+"comm.dao."+name+"Mapper";
            ServiceFileUtil.createService(en, packagesevice, servicemapper);
            ServiceFileUtil.createServiceImpl(en, packagesevice, servicemapper);
            System.out.println(name+"Service");
            ServiceFileUtil.createController(packagesevice+"."+name+"Service",packagecontroller,name+"Controller",name+"Service",name);
        }
    }

    /**
     * 同一类的生成在公共包下
     * @param names 公共实体
     * @param paname 实体共有包名
     * @throws Exception
     */
    public static void   init2(String[] names,String paname) throws Exception {
        for (String name:names) {
            name=name.replace("_","");//去掉下划线
            String lname=paname;
            System.out.println(lname);
            String en=basepath+"."+"comm.model."+name;
            String packagesevice=basepath+"."+lname+".service";
            String packagecontroller=basepath+"."+lname+".controller";
            String servicemapper=basepath+"."+"comm.dao."+name+"Mapper";
            ServiceFileUtil.createService(en, packagesevice, servicemapper);
            ServiceFileUtil.createServiceImpl(en, packagesevice, servicemapper);
            System.out.println(name+"Service");
            ServiceFileUtil.createController(packagesevice+"."+name+"Service",packagecontroller,name+"Controller",name+"Service",name);
        }
    }
    /**
     * ${servicemapper} mapperjava的地址
     * ${packageseviceImpl}
     * ${packagesevice}
     * ${serviceName}
     * ${serviceentity}
     * entityName
     * ${serviceinterface}

     * @throws Exception
     */
    public static void createService(String serviceentity,String packagesevice,String servicemapper ) throws Exception{
        String entityName=serviceentity.substring(serviceentity.lastIndexOf(".")+1,serviceentity.length());
        String serviceinterface=entityName+"Service";
        String sb=getFileTxt("templateservice");
        sb= StringUtils.replace(sb, "serviceentity",  serviceentity);
        sb= StringUtils.replace(sb, "entityName",  entityName);
        sb= StringUtils.replace(sb, "packagesevice",  packagesevice);
        sb= StringUtils.replace(sb, "serviceinterface",  serviceinterface);
        sb= StringUtils.replace(sb, "authorname",  authorname);
        sb= StringUtils.replace(sb, "createtime",  createtime);
        File f=new File(javapath+StringUtils.replace(packagesevice, ".", "\\")+"\\"+serviceinterface+".java");
        ServiceFileUtil.write(f, sb);
    }
    public static void createServiceImpl(String serviceentity,String packagesevice,String servicemapperAll) throws Exception{
        String entityName=serviceentity.substring(serviceentity.lastIndexOf(".")+1,serviceentity.length());
        String serviceImplName=entityName+"ServiceImpl";
        String serviceName=entityName+"Service";
        String servicemapper=servicemapperAll.substring(servicemapperAll.lastIndexOf(".")+1,servicemapperAll.length());
        String sb=getFileTxt("templateserviceImpl");
        sb= StringUtils.replace(sb, "serviceentity",  serviceentity);
        sb= StringUtils.replace(sb, "entityName",  entityName);
        sb= StringUtils.replace(sb, "packagesevice",  packagesevice+".impl");
        sb= StringUtils.replace(sb, "serviceinterfaceAll",  packagesevice+"."+serviceName);
        sb= StringUtils.replace(sb, "servicemapperAll",  servicemapperAll);
        sb= StringUtils.replace(sb, "servicemapper", servicemapper);
        sb= StringUtils.replace(sb, "serviceImplName", serviceImplName);
        sb= StringUtils.replace(sb, "serviceName", serviceName);
        sb= StringUtils.replace(sb, "authorname",  authorname);
        sb= StringUtils.replace(sb, "createtime",  createtime);
        File f=new File(javapath+StringUtils.replace(packagesevice, ".", "\\")+"\\impl\\"+serviceImplName+".java");
        ServiceFileUtil.write(f, sb);
    }
    /**
     * ${servicemapper} mapperjava的地址
     * ${packageseviceImpl}
     * ${packagesevice}
     * ${serviceName}
     * ${serviceentity}
     * entityName
     * ${serviceinterface}

     * @throws Exception
     */
    public static void createController(String tservice,String pagecontroller,String controllername,String servicename ,String name) throws Exception{
        String mappername=exChange(name);
        String sb=getFileTxt("templatecontroller");
        sb= StringUtils.replace(sb, "tservice",  tservice);
        sb= StringUtils.replace(sb, "pagecontroller",  pagecontroller);
        sb= StringUtils.replace(sb, "controllername",  controllername);
        sb= StringUtils.replace(sb, "servicename",  servicename);
        sb= StringUtils.replace(sb, "mappername",  mappername);
        sb= StringUtils.replace(sb, "entityname",  name);
        sb= StringUtils.replace(sb, "authorname",  authorname);
        sb= StringUtils.replace(sb, "createtime",  createtime);
        String path=javapath+StringUtils.replace(pagecontroller, ".", "\\")+"\\"+controllername+".java";
        System.out.println(path);
        File f=new File(path);
        ServiceFileUtil.write(f, sb);
    }

    /**
     *如果有前缀 单独处理  要求表中携带下滑线传递进来的实体名就有
     * @param mysqlurl
     * @param username
     * @param pwd
     * @param basepath
     * @param commtales
     * @throws Exception
     */
    public static void createMybatisXml(String mysqlurl,String username,String pwd,String basepath,String[] commtales,String prestr) throws Exception{
        String sb=getFileTxt("template_autogen");
        sb= StringUtils.replace(sb, "mysqlurl",  mysqlurl);
        sb= StringUtils.replace(sb, "username",  username);
        sb= StringUtils.replace(sb, "pwd",  pwd);
        sb= StringUtils.replace(sb, "commpage",  basepath);
        String realtables="";
        for (String table:commtales) {
        String tem="<table tableName=\"temtable\" domainObjectName=\"Entitytable\" enableCountByExample=\"false\" enableUpdateByExample=\"false\" enableDeleteByExample=\"false\" enableSelectByExample=\"false\" selectByExampleQueryId=\"false\"></table>";
            if(StringUtils.isNotBlank(prestr)){
            tem=StringUtils.replace(tem, "temtable",  exChangePre(table,prestr));//全部转为小写
            tem=StringUtils.replace(tem, "Entitytable",  table.replace("_",""));
            }else{
            tem=StringUtils.replace(tem, "temtable",  exChange(table));
            tem=StringUtils.replace(tem, "Entitytable",  table);
            }
            realtables+=tem;
        }
        sb= StringUtils.replace(sb, "commtales",  realtables);
       File f=new File(Mybatispath);
        ServiceFileUtil.write2(f, sb);
        runbat(Mybatisbat);
    }

    /**
     * 读取txt模板文件信息
     * @param filename 对应模板名称
     * @return
     * @throws Exception
     */
    public  static String getFileTxt(String filename) throws  Exception{
        BufferedReader read=null;
        StringBuffer stringBuffer=new StringBuffer();
        InputStreamReader isr = new InputStreamReader(new FileInputStream(new File(realpath+filename+".txt")), "UTF-8");
        //开始读取
        read = new BufferedReader(isr);
        String str=null;
        while ((str=read.readLine())!=null) {
            stringBuffer.append(str);
            stringBuffer.append("\n");
        }
        read.close();
        return  stringBuffer.toString();
    }
    public static void runbat(String strcmd){
        System.out.println(strcmd);
        Runtime rt = Runtime.getRuntime();
        Process ps = null;
        try {
            ps = rt.exec(strcmd);
            InputStreamReader isr=null;
            InputStream in = ps.getInputStream();
            isr=new InputStreamReader(in);
            //开始读取
            BufferedReader read = new BufferedReader(isr);
            String str="";
            while ((str=read.readLine())!=null) {
                System.out.println(str);
            }
            in.close();
            ps.waitFor();
        } catch (IOException e1) {
            e1.printStackTrace();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        int i = ps.exitValue();
        if (i == 0) {
            System.out.println("执行完成.") ;
        } else {
            System.out.println("执行失败.") ;
        }
        ps.destroy();
        ps = null;

        //批处理执行完后，根据cmd.exe进程名称 kill掉cmd窗口(这个方法是好不容易才找到了，网上很多介绍的都无效，csdn废我3分才找到这个方法)
       killProcess();

    }
    public static void killProcess(){
        Runtime rt = Runtime.getRuntime();
        Process p = null;
        try {
            rt.exec("cmd.exe /C start wmic process where name='cmd.exe' call terminate");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 不添加目录
     * @param file
     * @param data
     */
    public static void write2(File file,String data){
        try {
            if(!file.exists()){
                file.createNewFile();
            }
            OutputStream out=new FileOutputStream(file);
            BufferedWriter rd   =   new BufferedWriter(new OutputStreamWriter(out,Charset.forName("UTF-8")));
            rd.write(data);
            rd.close();
            out.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void write(File file,String data){
        try {
            String allpath=file.getPath();
            String subpath=allpath.substring(0,allpath.lastIndexOf("\\"));
            System.out.println(subpath);
            File tem=new File(subpath);
            if(!tem.exists()){
                if(!file.exists()){
                  tem.mkdirs();
                }
            }
            if(!file.exists()){
                file.createNewFile();
            }
            FileOutputStream out=new FileOutputStream(file,false); //如果追加方式用true
            out.write(data.getBytes("UTF-8"));//注意需要转换对应的字符集
            out.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //把一个字符串中的大写转为小写，小写转换为大写：思路1
    public static String exChange(String str){
        StringBuffer sb = new StringBuffer();
        if(str!=null){
            for(int i=0;i<str.length();i++){
                char c = str.charAt(i);
                if(Character.isUpperCase(c)){
                    sb.append(Character.toLowerCase(c));
                }else{
                    sb.append(c);
                }
            }
        }

        return sb.toString();
    }
    //把一个字符串中的大写转为小写，小写转换为大写：思路1 并添加前缀
    public static String exChangePre(String str,String prestr){
        StringBuffer sb = new StringBuffer();
        if(str!=null){
            for(int i=0;i<str.length();i++){
                char c = str.charAt(i);
                if(Character.isUpperCase(c)){
                    sb.append(Character.toLowerCase(c));
                }else{
                    sb.append(c);
                }
            }
        }

        return prestr+sb.toString();
    }
}